<?php 
 
namespace app\common\model;

use app\common\model\BaseModel;
use app\common\traits\ModelTrait;
use app\common\utils\JsonService;
/**
* This is the model class for table "{ptf_order}".
*
* @property int $order_id 订单id 
* @property string $order_sn 订单编号
* @property int $member_id 用户id 
* @property int $shop_id 店铺id 
* @property int $order_status 订单状态 
* @property int $shipping_status 发货状态 
* @property int $pay_status 支付状态 
* @property string $consignee 收货人
* @property int $country 国家 
* @property int $province 省份 
* @property int $city 城市 
* @property int $district 县区 
* @property int $twon 乡镇 
* @property string $address 地址
* @property string $zipcode 邮政编码
* @property string $mobile 手机
* @property string $email 邮件
* @property string $shipping_code 物流code
* @property string $shipping_name 物流名称
* @property string $pay_code 支付code
* @property string $pay_name 支付方式名称
* @property string $invoice_title 发票抬头
* @property int $goods_price 商品总价 
* @property int $shipping_price 邮费 
* @property int $user_money 使用余额 
* @property int $coupon_id 优惠券 对应coupon_list表id 
* @property int $coupon_price 优惠券抵扣 
* @property int $integral 使用积分 
* @property int $integral_money 使用积分抵多少钱 
* @property int $order_amount 应付款金额 
* @property int $total_amount 订单总价 
* @property int $add_time 下单时间 
* @property int $shipping_time 最后新发货时间 
* @property int $confirm_time 收货确认时间 
* @property int $pay_time 支付时间 
* @property string $transaction_id 第三方平台交易流水号
* @property int $order_prom_type 0默认1抢购2团购3优惠4预售5虚拟 
* @property int $order_prom_id 活动id 
* @property int $order_prom_amount 活动优惠金额 
* @property int $discount 价格调整 
* @property string $user_note 用户备注
* @property string $admin_note 管理员备注
* @property string $parent_sn 父单单号
* @property int $is_distribut 是否已分成0未分成1已分成 
* @property int $is_evaluate 是否评价 0为未评价 1为已评价 2为已追评 
* @property int $paid_money 订金 
* @property int $deleted 用户假删除标识,1:删除,0未删除 
*/
class Order extends BaseModel{

    protected $pk = 'order_id';
    protected $name = 'order';

    use ModelTrait;
    protected $autoWriteTimestamp = true;
    //protected $dateFormat = 'Y-m-d';
    //protected $createTime = 'create_time';
    //protected $updateTime = 'update_time';

    /**
    * {@inheritdoc}
    */
    public function attributeLabels()
    {
        return [
            'order_id' => '订单id',
            'order_sn' => '订单编号',
            'member_id' => '用户id',
            'shop_id' => '店铺id',
            'order_status' => '订单状态',
            'shipping_status' => '发货状态',
            'pay_status' => '支付状态',
            'consignee' => '收货人',
            'country' => '国家',
            'province' => '省份',
            'city' => '城市',
            'district' => '县区',
            'twon' => '乡镇',
            'address' => '地址',
            'zipcode' => '邮政编码',
            'mobile' => '手机',
            'email' => '邮件',
            'shipping_code' => '物流code',
            'shipping_name' => '物流名称',
            'pay_code' => '支付code',
            'pay_name' => '支付方式名称',
            'invoice_title' => '发票抬头',
            'goods_price' => '商品总价',
            'shipping_price' => '邮费',
            'user_money' => '使用余额',
            'coupon_id' => '优惠券 对应coupon_list表id',
            'coupon_price' => '优惠券抵扣',
            'integral' => '使用积分',
            'integral_money' => '使用积分抵多少钱',
            'order_amount' => '应付款金额',
            'total_amount' => '订单总价',
            'add_time' => '下单时间',
            'shipping_time' => '最后新发货时间',
            'confirm_time' => '收货确认时间',
            'pay_time' => '支付时间',
            'transaction_id' => '第三方平台交易流水号',
            'order_prom_type' => '0默认1抢购2团购3优惠4预售5虚拟',
            'order_prom_id' => '活动id',
            'order_prom_amount' => '活动优惠金额',
            'discount' => '价格调整',
            'user_note' => '用户备注',
            'admin_note' => '管理员备注',
            'parent_sn' => '父单单号',
            'is_distribut' => '是否已分成0未分成1已分成',
            'is_evaluate' => '是否评价 0为未评价 1为已评价 2为已追评',
            'paid_money' => '订金',
            'deleted' => '用户假删除标识,1:删除,0未删除',
        ];
    }

    public static function addOrder($user_id,$address_id,$shipping_code,$invoice_title,$coupon_id = 0,$car_price,$user_note='',$pay_name='',$goodsList=[]){
        // 仿制灌水 1天只能下 50 单  // select * from `tp_order` where user_id = 1  and order_sn like '20151217%'
        //$order_count = M('Order')->where("user_id",$user_id)->where('order_sn', 'like', date('Ymd')."%")->count(); // 查找购物车商品总数量
        //if($order_count >= 50)
        //    return array('status'=>-9,'msg'=>'一天只能下50个订单','result'=>'');

        // 0插入订单 order
        $address = MemberAddress::getOne(["address_id"=>$address_id]);

        $shipping = Shipping::getOne(['shipping_id'=>$shipping_code]);

        $order_sn = self::get_order_sn();
        $data = array(
            'order_sn'         => $order_sn, // 订单编号
            'member_id'          =>$user_id, // 用户id
            'shop_id'          =>$car_price['shop_id'], //商品id
            'consignee'        =>$address['consignee'], // 收货人
            'province'         =>$address['province'],//'省份id',
            'city'             =>$address['city'],//'城市id',
            'district'         =>$address['district'],//'县',
            'twon'             =>$address['twon'],// '街道',
            'address'          =>$address['address'],//'详细地址',
            'mobile'           =>$address['mobile'],//'手机',
            'zipcode'          =>$address['zipcode'],//'邮编',
            'email'            =>$address['email'],//'邮箱',
            'shipping_code'    =>$shipping_code,//'物流编号',
            'shipping_name'    =>$shipping['shipping_name'], //'物流名称',                为照顾新手开发者们能看懂代码，此处每个字段加于详细注释
            'invoice_title'    =>$invoice_title, //'发票抬头',
            'goods_price'      =>$car_price['goodsFee'],//'商品价格',
            'shipping_price'   =>$car_price['postFee'],//'物流价格',
            //'user_money'       =>$car_price['balance'],//'使用余额',
            'coupon_id'       =>$coupon_id,//'使用优惠劵ID',
            'coupon_price'     =>$car_price['couponFee'],//'使用优惠券',
            'integral'         =>$car_price['total_integral'], //'使用积分',
            //'integral_money'   =>$car_price['pointsFee'],//'使用积分抵多少钱',
            'total_amount'     =>($car_price['goodsFee'] + $car_price['postFee']),// 订单总额
            'order_amount'     =>$car_price['payables'],//'应付款金额',
            'add_time'         =>time(), // 下单时间
            //'order_prom_id'    =>$car_price['order_prom_id'],//'订单优惠活动id',
            //'order_prom_amount'=>$car_price['order_prom_amount'],//'订单优惠活动优惠了多少钱',
            'user_note'        =>$user_note, // 用户下单备注
            'pay_name'         =>$pay_name,//支付方式，可能是余额支付或积分兑换，后面其他支付方式会替换
        );
        $order = self::create($data);

        $data['order_id'] = $order_id = $order->order_id;
        $order = $data;//M('Order')->where("order_id", $order_id)->find();
        if(!$order_id)
            return array('code'=>-8,'msg'=>'添加订单失败','data'=>NULL);

        session('order_id',$order_id);
        // 1插入order_goods 表
        //$cartList = M('Cart')->where(['user_id'=>$user_id,'selected'=>1])->select();
        $cart_id = [];
        foreach($goodsList as $key => $val)
        {
            //$goods = Goods::where("goods_id", $val)->cache(true,1000)->find();
            $data2['order_id']           = $order_id; // 订单id
            $data2['goods_id']           = $val['goods_id']; // 商品id
            $data2['shop_id']            = $car_price['shop_id']; //商品id
            $data2['goods_name']         = $val['goods_name']; // 商品名称
            $data2['goods_sn']           = $val['goods_sn']; // 商品货号
            $data2['goods_num']          = $val['goods_num']; // 购买数量
            $data2['market_price']       = $val['market_price']; // 市场价
            $data2['goods_price']        = $val['shop_price']/$val['goods_num']; // 商品价               为照顾新手开发者们能看懂代码，此处每个字段加于详细注释
            $data2['original_img']        = $val['original_img']; //图片
            $data2['spec_key']           = $val['key']; // 商品规格
            $data2['spec_key_name']      = $val['key_name']; // 商品规格名称
            //$data2['member_goods_price'] = $val['member_goods_price']; // 会员折扣价
            $data2['cost_price']         = $val['cost_price']; // 成本价
            $data2['give_integral']      = $val['give_integral']; // 购买商品赠送积分
            $data2['discount_id']      = $val['discount_id']; // 购买商品赠送积分
            $data2['discount_goods_price'] = $val['real_price']/$val['goods_num']; // 购买商品赠送积分
            $data2['integral']           = $val['integral']; // 购买需要多少积分
            //$data2['prom_type']          = $val['prom_type']; // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
            //$data2['prom_id']            = $val['prom_id']; // 活动id
            $order_goods_id              = OrderGoods::create($data2);
            // 扣除商品库存  扣除库存移到 付完款后扣除
            //M('Goods')->where("goods_id = ".$val['goods_id'])->setDec('store_count',$val['goods_num']); // 商品减少库存
            $cart_id[] = $val['cart_id'];
        }

        // 2修改优惠券状态
        if($coupon_id > 0){
            $data3['member_id'] = $user_id;
            $data3['order_id'] = $order_id;
            $data3['use_time'] = time();
            $data3['status'] = 1;
            //M('CouponList')->where("id", $coupon_id)->save($data3);
            CouponList::updateOne($data3,['id'=>$coupon_id]);
            $cid = CouponList::getOne(['id'=>$coupon_id],'coupon_id');
            Coupon::where(['id'=>$cid['coupon_id']])->inc('use_num')->update(); // 优惠券的使用数量加一
        }

        // 3 扣除积分 扣除余额
        Member::where(['id'=>$user_id])->dec('integral',$car_price['total_integral'])->update();
        $data4 = [
            'member_id'=>$user_id,
            'shop_id' =>$car_price['shop_id'],
            'order_id'=>$order_id,
            'integral'=>$car_price['total_integral'],
            'type'=>2,
            'marks'=>'购物积分抵扣',
            'create_time'=>time(),
        ];
        IntegralRecord::create($data4);
        // 4 删除已提交订单商品
        Cart::delByWhere([['user_id','=',$user_id],['id','in',$cart_id]]);
        $return_arr = array('code'=>200,'msg'=>'计算成功','data'=>$order_id); // 返回结果状态

        return $return_arr;
    }


    /**
     * 获取订单 order_sn
     * @return string
     */
    public static function get_order_sn()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = self::where("order_sn = ".$order_sn)->count();
            if($order_sn_count == 0)
                break;
        }

        return $order_sn;
    }

    //获取关联shop
    public function getShop(){
        return $this->hasOne('Shop','shop_id','shop_id')->field('shop_id,shop_name');
    }

    /*
     * 关联获取order_goods;
     * */
    public function getOrderGoods(){
        return $this->hasMany('OrderGoods','order_id','order_id');
    }
}


?>